package com.hs.framework.base;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;

import java.util.ArrayList;
import java.util.List;

public abstract class BaseRecyclerAdapter<T> extends RecyclerView.Adapter<BaseRecyclerAdapter.BaseViewHolder> {

    protected List<T> dataList = new ArrayList<>();

    // 抽象方法，用于外部传入不同的布局资源 ID
    public abstract int getLayoutResId();

    // 抽象方法，用于外部绑定具体数据到视图上
    public abstract void bindData(BaseViewHolder holder, T data, int position);

    @NonNull
    @Override
    public BaseViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View view = LayoutInflater.from(parent.getContext()).inflate(getLayoutResId(), parent, false);
        return new BaseViewHolder(view);
    }

    @Override
    public void onBindViewHolder(@NonNull BaseViewHolder holder, int position) {
        T data = dataList.get(position);
        bindData(holder, data, position);
    }

    @Override
    public int getItemCount() {
        Log.d("getItemCount",dataList.size()+"");
        return dataList.size();
    }

    public static class BaseViewHolder extends RecyclerView.ViewHolder {

        public BaseViewHolder(@NonNull View itemView) {
            super(itemView);
        }
    }

    // 对外提供设置数据的方法
    public void setDataList(List<T> newDataList) {
        this.dataList = newDataList;
        notifyDataSetChanged();
    }

    // 对外提供添加单条数据的方法
    public void addData(T data) {
        dataList.add(data);
        notifyItemInserted(dataList.size() - 1);
    }

    // 对外提供移除数据的方法
    public void removeData(int position) {
        if (position >= 0 && position < dataList.size()) {
            dataList.remove(position);
            notifyItemRemoved(position);
        }
    }
}